<template>
  <div class="content-detail">
    <!-- <el-card v-if="!disabled">开工启动通知</el-card> -->
    <el-card class="card-box">
      <template #header v-if="isShowBase">
        <div class="card-box-header">
          <span>基础信息</span>
          <div v-if="show1" @click="show1 = !show1" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="show1 = !show1" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <div v-show="show1">
          <el-form
            :disabled="
              sectionInfo.startWorkStatus == '1' ||
              sectionInfo.startWorkStatus == '2' ||
              disabled
            "
            :model="formData"
            class="content-box"
            ref="formDataRef"
            :rules="rules"
            label-width="160px"
          >
            <el-form-item label="合同名称" prop="sectionName">
              {{ formData.sectionName }}
            </el-form-item>

            <el-form-item label="合同编号" prop="sectionCode">
              {{ formData.sectionCode }}
            </el-form-item>

            <el-form-item label="合同签署时间" prop="contractSignTime">
              <el-date-picker
                v-model.trim="formData.contractSignTime"
                type="datetime"
                placeholder="请选择日期"
                class="width-custom200"
                value-format="YYYY-MM-DD hh:mm:ss"
                clearable
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="合同验收时间" prop="contractAcceptTime">
              <el-date-picker
                v-model.trim="formData.contractAcceptTime"
                type="datetime"
                placeholder="请选择日期"
                class="width-custom200"
                value-format="YYYY-MM-DD hh:mm:ss"
                :disabled-date="disableDate"
                clearable
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="工程总负责人" prop="leaderName">
              <el-select
                v-model="formData.leaderName"
                filterable
                remote
                placeholder="请输入工程总负责人"
                :remote-method="getTableData"
                class="width-custom200"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="施工单位名称" prop="companyName">
              <el-select
                v-model="formData.companyName"
                filterable
                remote
                placeholder="请输入施工单位名称"
                :remote-method="getCompanyData"
                class="width-custom200"
              >
                <el-option
                  v-for="item in tableData"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="施工单位负责人" prop="partybHandlerName">
              <el-select
                v-model="formData.partybHandlerName"
                filterable
                remote
                placeholder="请输入施工单位负责人"
                :remote-method="getTableData2"
                class="width-custom200"
              >
                <el-option
                  v-for="item in userList2"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="施工单位联系电话" prop="companyPhone">
              <el-input
                v-model.trim="formData.companyPhone"
                class="width-custom200"
              ></el-input>
            </el-form-item>

            <el-form-item label="知会人" prop="notices">
              <el-select
                v-model="formData.notices"
                filterable
                remote
                placeholder="请输入知会人"
                :remote-method="getTableData3"
                class="width-custom200"
                multiple
              >
                <el-option
                  v-for="item in userList3"
                  :key="item.userId"
                  :label="item.name"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="合同简介" prop="sectionRemark">
              <el-input
                v-model.trim="formData.sectionRemark"
                type="textarea"
                :rows="10"
                v-if="
                  (sectionInfo.startWorkStatus == '0' ||
                    !sectionInfo.startWorkStatus) &&
                  !disabled
                "
              ></el-input>
              <span v-else>{{ formData.sectionRemark }}</span>
            </el-form-item>

            <div class="button-container">
              <el-button
                v-if="
                  (!sectionInfo.startWorkStatus ||
                    sectionInfo.startWorkStatus == '0') &&
                  !disabled
                "
                class="tempSaveButton"
                :loading="saveLoading"
                @click="judgeAddOrUpdate('1')"
                >暂存</el-button
              >
              <el-button
                v-if="
                  (!sectionInfo.startWorkStatus ||
                    sectionInfo.startWorkStatus == '0') &&
                  !disabled
                "
                class="startButton"
                type="primary"
                :loading="startLoading"
                @click="judgeAddOrUpdate('2')"
                >启动</el-button
              >
            </div>
          </el-form>
        </div>
      </el-collapse-transition>
    </el-card>
    <content-page
      v-if="formData.nodeStatusCode && isShowBase"
      :instanceId="formData.instanceId"
      :nodeDefId="formData.nodeStatusCode"
      :flowId="formData.flowId"
      :taskId="formData.taskId"
      :module="'inspection'"
      :flowType="'1031'"
      :billNum="formData.billNum"
      ref="contentRef"
      :isShowBase="false"
      :contractId="formData.id"
    ></content-page>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, defineProps, watch } from "vue";
// import { useRouter } from "vue-router";
import {
  startConstructionApi,
  addNewOperationApi,
  acquireDetailApi,
  updateDetailApi
} from "/@/api/startConstruction";
import ContentPage from "../../../approval/detail/content.vue";
// import { ProcessStatusEnum } from "../../../approval/types";
// import StatusInfo from "../../../approval/components/processInfo/StatusInfo.vue";
import NotifMessage from "/@/utils/message/notification";
import { storageLocal } from "/@/utils/storage";
import { getUserList } from "/@/api/user";
import { postSysCompanyList } from "/@/api/organization";

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  basicInfoData: {
    type: Object,
    default: () => {}
  },
  isShowBase: {
    type: Boolean,
    default: true
  }
});

// const formRef = ref<HTMLFormElement | null>(null) as any;
let tableData = ref([]);
// const contentRef = ref<HTMLFormElement | null>(null) as any;
// const router = useRouter();
let sectionInfo = reactive({
  startWorkStatus: "",
  startWorkId: ""
});
if (storageLocal.getItem("sectionInfo")) {
  sectionInfo = storageLocal.getItem("sectionInfo");
}
let projectInfo = storageLocal.getItem("projectInfo");
let show1 = ref(true);
let userList = ref([]);
let userList2 = ref([]);
let userList3 = ref([]);
let saveLoading = ref(false);
let startLoading = ref(false);

let formData: any = reactive({
  id: "",
  sectionName: sectionInfo?.sectionName,
  sectionCode: sectionInfo?.sectionCode,
  contractSignTime: "",
  contractAcceptTime: "",
  companyName: "" as any,
  leaderId: "",
  leaderName: "" as any,
  companyPhone: "",
  partybHandlerName: "" as any,
  partybHandlerId: "",
  sectionRemark: "",
  notices: "" as any,
  sectionId: sectionInfo?.id,
  projectManageId: projectInfo?.id,
  projectName: projectInfo?.projectName,
  saveStatus: "",
  nodeStatusCode: ""
});

const rules = {
  leaderName: [{ required: true, message: "工程总负责人", trigger: "change" }],
  companyName: [
    { required: true, message: "请选择施工单位名称", trigger: "change" }
  ],
  partybHandlerName: [
    { required: true, message: "请选择施工单位负责人", trigger: "change" }
  ],
  companyPhone: [
    { required: true, message: "请填写施工单位联系电话", trigger: "blur" }
  ]
};
const disableDate = time => {
  return time.getTime() < new Date(formData.contractSignTime).getTime();
};
//   const flowStatusOption = FlowStatusEnum;

// let total = ref<number>(0);
// let timeValue = ref(null);

// 格式化类型
// const formatterStatusType = row => {
//   return FlowStatusEnum[row.flowStatus].label;
// };
// const formatterStatusColor = row => {
//   return {
//     redColor: row.flowStatus === 0,
//     greenColor: row.flowStatus === 1,
//     grayColor: row.flowStatus === 2
//   };
// };

const tempSave = async type => {
  try {
    let json = { ...formData };
    json.leaderName = formData.leaderName.label;
    json.leaderId = formData.leaderName.value;
    json.partybHandlerName = formData.partybHandlerName.label;
    json.partybHandlerId = formData.partybHandlerName.value;
    json.companyName = formData.companyName.label;
    json.notices = JSON.stringify(formData.notices);
    delete json.id;
    json.saveStatus = type;
    const { code, message, data } = await addNewOperationApi(json);
    if (code == 200) {
      //cn.bing.com/?FORM=Z9FD1
      https: NotifMessage.success(message);
      formData.id = data;
      sectionInfo.startWorkId = formData.id;
      storageLocal.setItem("sectionInfo", sectionInfo);
      if (type == "2") {
        startConstruction();
      } else {
        saveLoading.value = false;
      }
    } else {
      if (type === "1") {
        saveLoading.value = false;
      } else {
        startLoading.value = false;
      }
      if (!message) return;
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
    if (type === "1") {
      saveLoading.value = false;
    } else {
      startLoading.value = false;
    }
  }
};

const startConstruction = async () => {
  try {
    let json = {
      leaderId: formData.leaderName.value,
      leaderName: formData.leaderName.label,
      companyId: formData.companyName.value,
      companyName: formData.companyName.label,
      partybHandlerId: formData.partybHandlerName.value,
      companyPhone: formData.companyPhone,
      partybHandlerName: formData.partybHandlerName.label,
      projectManageId: formData.projectManageId,
      projectName: formData.projectName,
      sectionId: formData.sectionId,
      id: formData.id
    };
    startConstructionApi(json)
      .then(res => {
        const { code, message } = res;
        if (code === 200) {
          NotifMessage.success(message);
          sectionInfo.startWorkStatus = "1";
          sectionInfo.startWorkId = formData.id;
          storageLocal.setItem("sectionInfo", sectionInfo);
          getDetailPage();
        } else {
          NotifMessage.error(message);
          startLoading.value = false;
        }
      })
      .catch(err => {
        NotifMessage.error(err);
        startLoading.value = false;
      });
  } catch (err) {
    console.log("err", err);
    startLoading.value = false;
  }
};

const getTableData = async (query = "") => {
  if (!query) {
    userList.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      userList.value = data.list.map(item => {
        return { value: item.id, label: `${item.name}(${item.userName})` };
      });
    }
  } catch (err) {
    console.log(err);
  }
};

const getTableData2 = async (query = "") => {
  if (!query) {
    userList2.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      userList2.value = data.list.map(item => {
        return { value: item.id, label: `${item.name}(${item.userName})` };
      });
    }
  } catch (err) {
    console.log(err);
  }
};

const getTableData3 = async (query = "") => {
  if (!query) {
    userList3.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      userList3.value = data.list.map(item => {
        return { userId: item.id, name: `${item.name}(${item.userName})` };
      });
    }
  } catch (err) {
    console.log(err);
  }
};

const getCompanyData = async (query = "") => {
  if (!query) {
    tableData.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      companyNameLike: query
    };
    const { code, data } = await postSysCompanyList(params);
    if (code === 200) {
      console.log(data, "data");
      tableData.value = data.list.map(item => {
        return { value: item.id, label: item.companyName };
      });
      console.log(tableData.value, "tableData.value");
    }
  } catch (err) {
    console.log(err);
  }
};

const getDetailPage = async () => {
  try {
    const { code, data } = await acquireDetailApi(formData.id);
    console.log(data, "data");
    if (code == 200) {
      // data.leaderName = {value: data.leaderId, label: data.leaderName};
      // data.companyName = {value: data.companyId, label: data.companyName};
      // data.partybHandlerName = {value: data.partybHandlerId, label: data.partybHandlerName};
      formData.id = data.id;
      formData.sectionName = data.sectionName;
      formData.sectionCode = data.sectionCode;
      formData.contractSignTime = data.contractSignTime;
      formData.contractAcceptTime = data.contractAcceptTime;
      formData.companyName = { value: data.companyId, label: data.companyName };
      formData.leaderName = { value: data.leaderId, label: data.leaderName };
      formData.companyPhone = data.companyPhone;
      formData.partybHandlerName = {
        value: data.partybHandlerId,
        label: data.partybHandlerName
      };
      formData.sectionRemark = data.sectionRemark;
      formData.sectionId = data.sectionId;
      formData.projectManageId = data.projectManageId;
      formData.projectName = data.projectName;
      tableData.value = [formData.companyName];
      userList.value = [formData.leaderName];
      userList2.value = [formData.partybHandlerName];
      userList3.value = JSON.parse(data.notices);
      formData.notices = userList3.value.map(function (item) {
        return item.userId;
      });
      sectionInfo.startWorkStatus = data.approveStatus;
      if (data.approveStatus != "0") {
        formData.nodeStatusCode = data.nodeStatusCode.toUpperCase();
        formData.instanceId = data.instanceId;
        formData.flowId = data.flowId;
        formData.taskId = data.taskId;
        formData.billNum = data.billNum;
      }
      startLoading.value = false;
      console.log("formData.notices", formData.notices);
    }
  } catch (err) {
    console.log(err);
    startLoading.value = false;
  }
};

if (sectionInfo?.startWorkId) {
  formData.id = sectionInfo.startWorkId;
  getDetailPage();
}

const updatePage = async type => {
  try {
    let json = { ...formData };
    json.leaderName = formData.leaderName.label;
    json.leaderId = formData.leaderName.value;
    json.partybHandlerName = formData.partybHandlerName.label;
    json.partybHandlerId = formData.partybHandlerName.value;
    json.companyName = formData.companyName.label;
    json.notices = JSON.stringify(formData.notices);
    json.saveStatus = type;
    const { code, message } = await updateDetailApi(json);
    if (code == 200) {
      NotifMessage.success(message);
      if (type == "2") {
        startConstruction();
      } else {
        saveLoading.value = false;
      }
    } else {
      if (type === "1") {
        saveLoading.value = false;
      } else {
        startLoading.value = false;
      }
      if (!message) return;
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
    if (type === "1") {
      saveLoading.value = false;
    } else {
      startLoading.value = false;
    }
  }
};

const judgeAddOrUpdate = (type: any) => {
  if (type === "1") {
    saveLoading.value = true;
  } else {
    startLoading.value = true;
  }
  if (formData.id) {
    updatePage(type);
  } else {
    tempSave(type);
  }
};

watch(
  () => props.basicInfoData,
  newVal => {
    if (newVal && newVal.id) {
      formData.id = newVal.id;
      sectionInfo.startWorkStatus = formData.approveStatus;
      sectionInfo.startWorkId = formData.id;
      getDetailPage();
    }
  },
  {
    deep: true,
    immediate: true
  }
);
// const getCompanyList = async (obj: object = {}) => {
//   try {
//     const { code, data } = await postSysCompanyList(obj);
//     if (code === 200) {
//       tableData = data.list;
//     }
//   } catch (err) {
//     console.log(err);
//   }
// }
// getCompanyList();

// const getTableList = async (obj: object = {}) => {
//   try {
//     loading.value = true;
//     const { code, data } = await postComFlowList(obj);
//     if (code === 200) {
//       tableData.value = data.list;
//       total.value = data.rows;
//     }
//   } catch (err) {
//     console.log(err);
//   } finally {
//     loading.value = false;
//   }
// };

// const handleChangeDate = item => {
//   console.log(item, "date");
//   if (item) {
//     formInline.createTimeStrStart = item[0];
//     formInline.createTimeStrEnd = item[1];
//   } else {
//     formInline.createTimeStrStart = "";
//     formInline.createTimeStrEnd = "";
//   }
// };

// const handleReset = () => {
//   formRef.value.resetFields();
//   timeValue.value = null;
//   handleChangeDate(null);
// };

// const handleSearch = () => {
//   getTableList(formInline);
//   handleChangeDate(null);
// };

// const handleAdd = () => {
//   dialogVisible.value = true;
// };

// const handleToDetail = (code: number): void => {
//   router.replace({
//     path: "/acceptance/material/detail",
//     query: { mode: "add", nodeDefId: "ACT_010", flowMinType: code }
//   });
// };

// const handleDetail = row => {
//   const { id, flowId, nodeDefId, instanceId, preNodeId, flowMinType } = row;
//   router.replace({
//     path: "/acceptance/material/detail",
//     query: {
//       mode: "read",
//       contractId: id,
//       flowId,
//       nodeDefId: instanceId ? nodeDefId.toUpperCase() : "ACT_010",
//       instanceId,
//       preNodeId,
//       flowMinType
//     }
//   });
// };

// const handleDelete = async row => {
//   try {
//     const params = {
//       id: row.id
//     };
//     const { code, message } = await postComFlowDelete(params);
//     if (code === 200) {
//       NotifMessage.success(message);
//       getTableList(formInline);
//     } else {
//       NotifMessage.error(message);
//     }
//   } catch (err) {
//     console.log(err);
//   }
// };

// getTableList(formInline);
</script>
<style scoped lang="scss">
.dialog__row {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.button-container {
  width: 100%;
  height: 35px;
  display: flex;
  flex-direction: row;
  justify-content: right;
}
</style>
